<?php

namespace App\Models\Admin;

use App\Models\Api\StoreCart;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Goods extends Model
{
    protected $table = 'goods';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $fillable = [
        'goods_name', 'goods_sn', 'goods_price', 'goods_img', 'goods_img_list',
        'goods_detail', 'goods_specification', 'goods_unit', 'goods_total_num',
        'goods_sale_num', 'cate_id', 'status', 'is_group', 'promotion',
        'fixed_price', 'mini_quantity', 'send', 'send_require', 'goods_weight_j',
        'goods_weight_m'
    ];
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    public function getTable()
    {
        return $this->prefix . $this->table;
    }

    /**
     * 获取单品信息
     * @param $id
     * @return mixed
     */
    public static function getInfoById($id)
    {
        $info = self::from('goods as g')
            ->select(['g.*', 'c.cate_name'])
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where(['g.id' => $id])
            ->first();
        $info->first_store_product_batch =  '';
        if ($info) {
            // 查找该商品最早的入库批次时间
            $firstBatch = \DB::table('stock_order_goods as sog')
                ->join('stock_order as so', 'so.id', '=', 'sog.order_id')
                ->where('sog.goods_id', $id)
                ->orderBy('so.store_product_batch', 'asc')
                ->value('so.store_product_batch');
            $info->first_store_product_batch = $firstBatch ?: '';
        }

        return $info;
    }

    /**
     * 获取产品的基本信息
     */
    public static function getBaseList()
    {
        $list = self::from('goods as g')
            ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.mini_quantity', 'g.goods_price', 'g.goods_img', 'g.fixed_price', 'c.cate_name'])
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->get();

        return $list;
    }

    /**
     * 所有商品商品库存
     * @return mixed
     */
    public static function getRepertoryList()
    {
        $list = self::from('goods as g')
            ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.goods_price', 'g.mini_quantity', 'g.fixed_price', 'c.cate_name', 'g.goods_total_num', 'g.goods_sale_num'])
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->get();
        return $list;
    }

    /**
     * 商品商品库存
     * @return mixed
     */
    public static function getPageRepertoryList($where, $limit = 15)
    {
        $table = self::getTableName();
        $offset = ($limit > 0) ? (request()->get('page', 1) - 1) * $limit : 0;
        
        // 构建WHERE条件
        $conditions = ["g.status = 1"];
        $params = [];
        
        if (!empty($where['name'])) {
            $conditions[] = "g.goods_name LIKE ?";
            $params[] = "%{$where['name']}%";
        }
        if (!empty($where['goods_sn'])) {
            $conditions[] = "g.goods_sn = ?";
            $params[] = $where['goods_sn'];
        }

        // 构建基础SQL
        $sql = "SELECT 
            g.id, 
            g.goods_sn, 
            g.goods_img, 
            g.goods_name,
            g.mini_quantity,
            g.goods_price,
            g.is_group,
            g.goods_group,
            g.promotion,
            g.goods_type,
            c.cate_name,
            g.goods_total_num,
            g.goods_sale_num,
            CASE 
                WHEN g.is_group = 1 THEN '组合商品'
                WHEN g.promotion = 1 THEN '促销商品'
                WHEN g.goods_type = 2 THEN '精品'
                WHEN g.goods_type = 3 THEN '特选'
                ELSE '普通商品' 
            END as goods_type_name
        FROM e_goods as g
        LEFT JOIN e_goods_category as c ON c.id = g.cate_id
        WHERE " . implode(' AND ', $conditions) . "
        AND g.is_group = 0
        AND NOT EXISTS (
            SELECT 1 
            FROM e_goods as sub_g
            WHERE FIND_IN_SET(g.id, sub_g.goods_group)
        )";

        // 获取总记录数
        $countSql = "SELECT COUNT(*) as total FROM ({$sql}) as temp";
        $total = DB::select($countSql, $params)[0]->total;

        // 添加分页
        if ($limit > 0) {
            $sql .= " ORDER BY g.id DESC LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;
        }

        // 执行查询并转换为数组
        $results = DB::select($sql, $params);
        $list = array_map(function($item) {
            $array = (array)$item;
            // 处理组合商品的实际库存
            if ($array['is_group'] == 1 && !empty($array['goods_group'])) {
                $array['real_stock'] = self::calculateGroupStock((object)$array);
            }
            return $array;
        }, $results);

        // 构建分页数据
        if ($limit > 0) {
            $paginator = new \Illuminate\Pagination\LengthAwarePaginator(
                $list,
                $total,
                $limit,
                request()->get('page', 1),
                ['path' => request()->url()]
            );
            return $paginator;
        }

        return $list;
    }

    /**
     * 计算组合商品实际可用库存
     */
    private static function calculateGroupStock($goods)
    {
        if (empty($goods->goods_group)) {
            return 0;
        }

        $subGoodsIds = explode(',', $goods->goods_group);
        $minStock = PHP_INT_MAX;

        foreach ($subGoodsIds as $subGoodsId) {
            $subGoods = self::find($subGoodsId);
            if (!$subGoods) {
                continue;
            }
            $minStock = min($minStock, $subGoods->goods_sale_num);
        }

        return $minStock == PHP_INT_MAX ? 0 : $minStock;
    }

    /**
     * 获取商户设置的商品价格
     * @param $store_id
     * @return mixed
     */
    public static function getGoodsStoreList($store_id)
    {
        $list = self::from('goods_store as s')
            ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.goods_price', 'g.goods_img', 'g.fixed_price', 'g.promotion', 'c.cate_name', 's.mini_quantity', 's.sale_price', 's.buy_num', 's.get_num'])
            ->where(['s.store_id' => $store_id])
            ->get();
        return $list;
    }

    /**
     * 获取商品列表
     * 获取未添加的商品
     * @param $store_id
     */
    public static function getNewGoodsStoreList($store_id, $discount_rate = 1)
    {
        $db = self::from('goods as g')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.mini_quantity', 'g.goods_price', 'g.goods_img', 'g.fixed_price', 'g.promotion', 'c.cate_name']);
//            ->where(['g.status' => 1]);
        $glist = GoodsStore::select('goods_id')->where('store_id', $store_id)->get()->toArray();
        if ($glist) {
            foreach ($glist as $item) {
                $ids[] = $item['goods_id'];
            }
            $db->whereNotIn('g.id', $ids);
        }
        $list = $db->get()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]['buy_num'] = 1;
            $list[$key]['get_num'] = 1;
            if ($item['fixed_price'] == 1) {
                $list[$key]['sale_price'] = $item['goods_price'];
            } else {
                $list[$key]['sale_price'] = ceil($discount_rate * $item['goods_price'] * 100) / 100;
            }
        }
        return $list;
    }

    /**
     * 获取列表
     * @param array $where
     * @return mixed
     */
    public static function getList($where = [], $limit = 15)
    {
        $db = self::from('goods as g')->where([]);
        if (isset($where['goods_name']) && !empty($where['goods_name'])) {
            $db->where('g.goods_name', 'like', '%' . trim($where['goods_name']) . '%');
        }
        if (isset($where['is_group']) && $where['is_group'] !== null) {
            $db->where('g.is_group', $where['is_group']);
        }
        if (isset($where['promotion']) && $where['promotion'] !== null) {
            $db->where('g.promotion', $where['promotion']);
        }
        if (isset($where['status']) && $where['status'] !== null) {
            $db->where('g.status', $where['status']);
        }

        // 添加调试信息
        \Log::info('Goods List Query:', [
            'sql' => $db->toSql(),
            'bindings' => $db->getBindings(),
            'where' => $where
        ]);

        $result = $db->leftjoin('goods_category as c', 'g.cate_id', '=', 'c.id')
            ->select('g.*', 'c.cate_name')
            ->orderBy('g.id', 'desc')
            ->paginate($limit);
        return $result;
    }

    /**
     * 获取所有商品
     */
    public static function getAll($where = [])
    {
        $db = self::from('goods as g')->where([]);
        if (isset($where['goods_name']) && !empty($where['goods_name'])) {
            $db->where('g.goods_name', trim($where['goods_name']));
        }

        $result = $db->select('g.id', 'g.goods_name', 'g.goods_sn', 'g.goods_price', 'g.is_group', 'g.promotion', 'g.goods_sale_num')
            ->orderBy('g.id', 'desc')
            ->get()
            ->toArray();
        return $result;
    }

    /**
     * 获取商品详情
     * @param array $where
     * @return mixed
     */
    public static function getInfo($param = [])
    {
        $where = [];
        if (isset($param['id']) && $param['id'] !== null) {
            $where['id'] = (int)$param['id'];
        }
        if (isset($param['goods_sn']) && $param['goods_sn'] !== null) {
            $where['goods_sn'] = trim($param['goods_sn']);
        }
        if (!count($where)) {
            return [];
        }

        $result = self::where($where)->orderBy('id', 'asc')->first();
        return $result;
    }

    /**
     * 添加商品
     * @param array $where
     * @return mixed
     */
    public static function add($info)
    {
        $time = time();
        $info['updated_at'] = $time;
        $info['created_at'] = $time;

        $goods_id = self::insertGetId($info);
        if ($goods_id) {
            $nowTime = time();
            $storeList = Store::where([])->select(['id', 'discount_rate'])->get()->toArray();
            foreach ($storeList as $store) {
                $sinfo['store_id'] = $store['id'];
                $sinfo['goods_id'] = $goods_id;
                if ($info['fixed_price'] == 1 || $info['promotion'] == 1) {
                    $sinfo['sale_price'] = $info['goods_price'];
                } else {
                    $sinfo['sale_price'] = $info['goods_price'] * $store['discount_rate'];
                }
                $sinfo['buy_num'] = 1;
                $sinfo['mini_quantity'] = $info['mini_quantity'];
                $sinfo['get_num'] = 0;
                $sinfo['created_at'] = $nowTime;
                GoodsStore::insert($sinfo);
            }
            return $goods_id;
        }
        return false;
    }

    /**
     * 编辑商品
     * @param $id
     * @param $info
     * @return mixed
     */
    public static function edit($id, $info)
    {
        $info['updated_at'] = time();
        if ($info['fixed_price'] == 1 || $info['promotion'] == 1) {
            GoodsStore::where(['goods_id' => $id])->update(['sale_price' => $info['goods_price']]);
        }
        if ($info['status'] != 1) {
            StoreCart::where(['goods_id' => $id])->delete();
            StoreCart::where(['goods_pid' => $id])->delete();
        }
        // 最低起订量
        $mini_quantity = self::where(['id' => $id])->value('mini_quantity');
        if ($mini_quantity != $info['mini_quantity']) {
            GoodsStore::where(['goods_id' => $id])->update(['mini_quantity' => $info['mini_quantity']]);
        }
        return self::where(['id' => $id])->update($info);
    }

    /**
     * 删除商品
     * @param $id
     * @return mixed
     */
    public static function del($id)
    {
        return self::where(['id' => $id])->delete();
    }

    public static function getTableName()
    {
        return (new self())->getTable();
    }
}
